<template >
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon></el-alert>
      <el-row class="cascader">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="arrKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleCateChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled=" tabsDisabled" @click="addDialogVisibleShow">添加参数</el-button>
          <el-table :data="manyTabsData" border style="width: 100%">
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  type="warning"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editShow(scope.row)"
                >编辑</el-button>

                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="Delete(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled=" tabsDisabled" @click="addDialogVisibleShow">添加属性</el-button>

          <el-table :data="onlyTabsData" border style="width: 100%">
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  type="warning"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editShow(scope.row)"
                >编辑</el-button>

                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="Delete(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 动态静态添加按钮共用对话框 -->
    <el-dialog :title="'添加'+textTitle" :visible.sync="addDialogVisible" width="50%">
      <el-form :model="addRuleForm" :rules="addRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="textTitle" prop="attr_name">
          <el-input v-model="addRuleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="Add">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog
      :title="'修改'+textTitle"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editClose"
    >
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="textTitle" prop="attr_vals">
          <el-input v-model="editForm.attr_vals"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="Edit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      arrKeys: [],
      cateProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      //动态数据
      manyTabsData: [],
      //静态数据
      onlyTabsData: [],
      //控制tabs默认显示哪个页面，文档里面动态为many，静态为only
      activeName: "many",

      addDialogVisible: false,

      //编辑显示控制
      editDialogVisible: false,
      //存放添加按钮的双向绑定数据
      addRuleForm: {
        attr_name: ""
      },
      //存放编辑按钮的双向绑定数据
      editForm: {},
      //添加按钮表单的验证规则
      addRules: {
        attr_name: [{ required: true, message: "请输入内容", trigger: "blur" }]
      },
      editRules: {
        attr_name: [{ required: true, message: "请输入内容", trigger: "blur" }]
      }
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return;
      } else {
        this.cateList = res.data;
      }
    },
    //级联选择框选中变化的时候，会出发这个函数
    handleCateChange() {
      this.getTabsData();
    },
    //tab页签点击事件的处理函数
    handleClick() {
      this.getTabsData();
    },
    async getTabsData() {
      //一定要要选择第三级分类，id才会北部奥村到arrKeys数组中，否则为空
      if (this.arrKeys.length !== 3) {
        this.arrKeys = [];
        return;
      }
      console.log(this.arrKeys);
      const { data: res } = await this.$http.get(
        `categories/${this.getTabsId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      );
      if (res.meta.status !== 200) {
        return;
      } else {
        //在显示表数据前处理attr_vals中的数据，把里面的字符串分割成数组后，遍历出来
        res.data.forEach(item => {
          //   通过三元表达式判断attr_vals是否为空
          item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];

          item.inputVisible = false;
          item.inputValue = "";
          console.log(item);
        });
        if (this.activeName === "many") {
          this.manyTabsData = res.data;
        } else {
          this.onlyTabsData = res.data;
        }
      }
    },
    //控制点击动态静态后显示对话框事件
    addDialogVisibleShow() {
      this.addDialogVisible = true;
    },
    //点击确定调用API添加参数
    Add() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return;
        } else {
          const { data: res } = await this.$http.post(
            `categories/${this.getTabsId}/attributes`,
            {
              attr_name: this.addRuleForm.attr_name,
              attr_sel: this.activeName
            }
          );
          if (res.meta.status !== 201) {
            console.log(res.meta);

            return this.$message.error("添加失败");
          } else {
            this.$message.success("添加成功");

            this.addDialogVisible = false;
            this.getTabsData();
          }
        }
      });
    },
    //按下enter或失去焦点时出发的事件
    handleInputConfirm(row) {
      //length不能忘，不然按回车的时候有bug
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      } else {
        row.attr_vals.push(row.inputValue.trim());
        row.inputValue = "";
        row.inputVisible = false;
        //没有return，则证明输入内容有效，需要做后续处理
        this.putAttrvals(row);
      }
    },
    //发起编辑API修改模块，（row）不要忘了
    async putAttrvals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.getTabsId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" ") //以字符串的形式存储，所以要把数组转换为字符串数组
        }
      );
      if (res.meta.status !== 200) {
        return;
      } else {
        this.$message.success("修改参数成功");
      }
    },
    //删除tag标签参数
    handleClose(i, row) {
      row.attr_vals.splice(i, 1);
      this.putAttrvals(row);
    },
    //点击后显示tag输入框
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //编辑对话框
    async editShow(row) {
      const {
        data: res
      } = await this.$http.get(
        `categories/${this.getTabsId}/attributes/${row.attr_id}`,
        { params: { attr_sel: this.activeName } }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数失败");
      } else {
        this.editForm = res.data;
        this.editDialogVisible = true;
      }
    },
    //点击确定后编辑参数
    Edit() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return;
        } else {
          const { data: res } = await this.$http.put(
            `categories/${this.getTabsId}/attributes/${this.editForm.attr_id}`,
            {
              attr_name: this.editForm.attr_name,
              attr_sel: this.activeName,
              attr_vals: this.editForm.attr_vals
            }
          );
          if (res.meta.status !== 200) {
            return this.$message.error("更新失败");
          } else {
            this.$message.success("更新成功");
            this.getTabsData();
            this.editDialogVisible = false;
          }
        }
      });
    },
    //关闭编辑窗口重置
    editClose() {
      this.$refs.editFormRef.resetFields();
    },
    //删除
    async Delete(row) {
      const result = await this.$confirm(
        "此操作将永久删除该" + this.textTitle + ", 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(error => error);
      if (result !== "confirm") {
        return;
      } else {
        const { data: res } = await this.$http.delete(
          `categories/${this.getTabsId}/attributes/${row.attr_id}`
        );
        if (res.meta.status !== 200) {
          return this.$message.err("删除失败");
        } else {
          this.$message.success("删除成功");
          this.getTabsData();
        }
      }
    }
  },
  computed: {
    //当cascader不是3级时候，Tabs禁止使用
    tabsDisabled() {
      if (this.arrKeys.length !== 3) {
        return true;
      } else {
        return false;
      }
    },
    //总是输出第三级的数据
    getTabsId() {
      if (this.arrKeys.length === 3) {
        return this.arrKeys[2];
      } else {
        return null;
      }
    },
    //监听公用对话框是输出many还是only数据
    textTitle() {
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    }
  }
};
</script>

<style lang="less" scoped>
.cascader {
  margin: 15px 0;
}
.input-new-tag {
  width: 120px;
}
.el-tag {
  margin: 0 15px;
}
</style>